<template>
	<div id="startup">
		<el-form :inline="true" class="demo-form-inline">
			<el-row >
				<el-col>
					<el-form-item label="查询名称：">
						<el-input v-model="searchName" placeholder="请输入内容"></el-input>
					</el-form-item>
					<el-form-item label="key：">
						<el-input v-model="key" placeholder="请输入内容"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col>
					<el-button type="primary" @click="search">查询</el-button>
					<el-button type="primary" @click="state(0)">禁用</el-button>
					<el-button type="primary" @click="state(1)">启用</el-button>
					<el-button type="primary" @click="newlyAdded">新增</el-button>
				</el-col>
			</el-row>
		</el-form>

		<div class="mt-3">
			<template>
				<el-table :data="tableData" border style="width: 100%" @selection-change="selectChange">
					<el-table-column type="selection" width="55"></el-table-column>
					<el-table-column prop="name" label="名称"></el-table-column>
					<el-table-column prop="keyVal" label="key"></el-table-column>
					<el-table-column prop="creator" label="创建人" width="180"></el-table-column>
					<el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
					<el-table-column prop="status" label="状态" width="180"></el-table-column>
					<el-table-column prop="url" label="地址" width="180"></el-table-column>
					<el-table-column label="操作" width="150">
						<template scope="scope">
							<el-button type="text" size="small" @click="editConent(scope.row)">编辑</el-button>
						</template>
					</el-table-column>
				</el-table>
			</template>
		</div>
		<div class="pagination">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currentPage.page" :page-sizes="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</div>
		<div class="add-dialog" :class="{newly:isNewly}">
			<div class="add-dialog-conent">
				<div class="el-dialog__header">
					<span class="el-dialog__title">{{dialogName}}</span>
					<button type="button" aria-label="Close" class="el-dialog__headerbtn" @click="handleClose">
						<i class="el-dialog__close el-icon el-icon-close"></i>
					</button>
				</div>
				<div class="table-title mar-lef10">
					<el-form :inline="true" class="demo-form-inline" label-width="200px">
						<el-row >
							<el-col>
								<el-form-item label="新增模板名称：">
									<el-input v-model="ruleForm.newlyAddName" placeholder="请输入内容"></el-input>
									<b style="color: red;font-size: 12px;">*必填项</b>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row >
							<el-col>
								<el-form-item label="新增模板key：">
									<el-input v-model="ruleForm.addKey" placeholder="请输入内容"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row >
							<el-col>
								<el-form-item label="微服务地址：">
									<el-input v-model="ruleForm.micAddress" placeholder="请输入内容"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row >
							<el-col>
								<el-form-item label="请求方式">
									 <el-select v-model="ruleForm.requestMode" placeholder="请选择" :disabled="requestDisabled">
									    <el-option
									      v-for="item in request"
									      :key="item.value"
									      :label="item.label"
									      :value="item.value">
									    </el-option>
									  </el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row >
							<el-col>
								<el-form-item label="状态：">
									<el-select name="" v-model="ruleForm.status">
										<el-option v-for="(item, index) in ['禁用','启用']" 
											:label="item" 
											:key="item.index" 
											:value="index"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>

				</div>

				<div class="pop">
					<h2>上传</h2>
					<p class="ml-3">
						<el-button type="primary" id="browse">选择文件</el-button>
						<el-button type="success" id="upload-btn">开始上传</el-button>
						<!--<button id="upload-btn1">暂停</button>-->
					</p>
					<ul id="file-list"></ul>
				</div>
				<div class="model"></div>

				<!--<div class="el-message-box__btns">
					<button type="button" class="el-button el-button--default el-button--small" >
						<span @click="isNewly=false">取消</span>
					</button>
					<button type="button" class="el-button el-button--default el-button--small el-button--primary ">
						<span > 确定</span>
					</button>
				</div>-->
			</div>
		</div>

		<div class="edit-dialog" :class="{show:isEditDialog}">
			<div class="add-dialog-conent">
				<div class="el-dialog__header">
					<span class="el-dialog__title">{{dialogName}}</span>
					<button type="button" aria-label="Close" class="el-dialog__headerbtn" @click="handleClose">
						<i class="el-dialog__close el-icon el-icon-close"></i>
					</button>
				</div>
				<div class="table-title mar-lef10">
					<el-form :inline="true" class="demo-form-inline" label-width="200px" >
					<el-row >
							<el-col>
								<el-form-item label="编辑模板名称：">
									<el-input v-model="edit.newlyAddName" placeholder="请输入内容"></el-input>
									<b style="color: red;font-size: 12px;">*必填项</b>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row >
							<el-col>
								<el-form-item label="编辑模板key：">
									<el-input v-model="edit.addKey" placeholder="请输入内容"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row >
							<el-col>
								<el-form-item label="微服务地址：">
									<el-input v-model="edit.micAddress" placeholder="请输入内容"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row >
							<el-col>
								<el-form-item label="状态：">
									<el-select name="" v-model="edit.status">
										<el-option v-for="(item, index) in ['禁用','启用']" 
											:label="item" 
											:key="item.index" 
											:value="index"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
					<!--<ul>
						<li>
							<span>编辑模板名称：</span>
							<input type="text" placeholder="请输入内容" v-model="edit.newlyAddName" />
							<b style="color: red;font-size: 12px;">*必填项</b>
						</li>
					</ul>
					<ul>
						<li class="prohibit-input">
							<span>key：</span>
							<input type="text" placeholder="请输入内容" v-model="edit.addKey" />
						</li>
					</ul>-->
					
					<!--<ul>
						<li>
							<span>状态：</span>
							<select name="" v-model="edit.status">
								<option :value="0">禁用</option>
								<option :value="1">启用</option>
							</select>
						</li>
					</ul>-->
				</div>
				<div class="el-message-box__btns">
					<button type="button" class="el-button el-button--default el-button--small">
						<span @click="isEditDialog=false">取消</span>
					</button>
					<button type="button" class="el-button el-button--default el-button--small el-button--primary ">
						<span  @click="editCom">提交</span>
					</button>
				</div>
				<!--<div class="pop">
					<h2>上传</h2>
					<p>
						<button id="browse">选择文件</button>
						<button id="upload-btn">开始上传</button>
					</p>
					<ul id="file-list"></ul>
				</div>
				<div class="model"></div>-->
			</div>
		</div>

	</div>
</template>

<script>
	import qs from 'qs'
	export default {
		name: 'formTemplate',
		data() {
			return {
				requestDisabled:true,
				request:[{
			    value: 'get',
                label: 'get请求'
				},{
			    value: 'post',
                label: 'post请求'
				}],
				searchName: '',
				key: '',
				tableData: [],
				currentPage: {
					page: 1,
					pageNum: 10,
				},
				pageSize: ['10', '15', '50'],
				total: 0,
				selectData: [],
				ruleForm: {
					newlyAddName: '',
					addKey: '',
					status: 0,
					micAddress:'',
					requestMode:'',
				},
				edit: {
					newlyAddName: '',
					addKey: '',
					status: '',
					id:'',
					micAddress:'',
				},
				isNewly: false,
				dialogName: '',
				isEditDialog: false,
				judgeUpload:false
			}
		},
		watch:{
			'ruleForm.micAddress':function(value){
				var vm =this
				if(vm.ruleForm.micAddress.length>4){
					vm.requestDisabled = false;
				}else{
					vm.requestDisabled = true;
				}
			}
		},
		mounted: function() {
			var _this = this
			var uploader = new plupload.Uploader({
				browse_button: 'browse', //触发文件选择对话框的按钮，为那个元素id
				url: "http://localhost/activiti-web/form/uploadFile", //服务器端的上传页面地址
				runtime: 'post',
				flash_swf_url: 'js/Moxie.swf', //swf文件，当需要使用swf方式进行上传时需要配置该参数
				silverlight_xap_url: 'js/Moxie.xap', //silverlight文件，当需要使用silverlight方式进行上传时需要配置该参数
				// Maximum file size
				max_file_size: '10m',
				drop_element: '.pop',
				chunk_size: 0,
				drop_element: 'file-list',
				multipart: true,
				use_http_method: 'post',
				filters: {
					max_file_size: 10240000,
					prevent_duplicates: false,
					//不允许选取重复文件
					mime_types: [ //只允许上传图片和zip文件
						{
							title: "Form files",
							extensions: "form"
						},

					],
				},
				multi_selection: false,
			});
			//在实例对象上调用init()方法进行初始化
			uploader.init();
			//绑定文件添加进队列事件
			uploader.bind('FilesAdded', function(uploader, files) {
				_this.ruleForm.addKey = files[0].name;
				console.log(uploader);
				console.log(files)
				console.log(_this.judgeUpload)
				console.log(uploader.files.length)
				if(_this.judgeUpload == false){
					if(uploader.files.length > 1) {
					files = []
					_this.$message({
						message: "每次只能上传一个文件！",
						type: 'error'
					});
					$('#browse').attr({
						"disabled": "disabled"
					});
					$('#upload-btn').attr({
						"disabled": "disabled"
					});
					$('#browse').addClass("is-disabled");
					$('#upload-btn').addClass("is-disabled");
//					upload-btn
//					_this.judgeUpload = false;
				}
				}else{
					files =[],
					_this.judgeUpload = false;
				}
				
				for(var i = 0, len = files.length; i < len; i++) {
					var file_name = files[i].name; //文件名
					var str = "<a class='pic_delete' data-val='" + files[i].id + "'>删除</a>";
					//构造html来更新UI
					var html = '<li id="' + files[i].id + '" class="file" ><p class="file-name">' + file_name + '' + str + '</p><p class="progress"></p></li>';
					$(html).appendTo('#file-list');
				}
			});
			$(document).on('click', '.pic_delete', function() {
				$(this).parent().remove();
				var toremove = '';
				var id = $(this).attr("data-val");
				for(var i in uploader.files) {
					if(uploader.files[i].id === id) {
						toremove = i;
					}
				}
				$('#' + id + '').hide(); //控制进度条
				uploader.files.splice(toremove, 1);
			});
			//绑定文件上传进度事件
			uploader.bind('UploadProgress', function(uploader, file) {
				$('#' + file.id + ' .progress').css('width', file.percent + '%'); //控制进度条
				$('#' + file.id + ' .progress').text(file.percent + '%'); //控制进度条
			});
			//上传错误
			uploader.bind('Error', function(uploader, err) {
				switch(err.code) {
					case 5:
						_this.$message({
							message: "上传完成！",
							type: 'success'
						});
						break;
					case -601:
						_this.$message({
							message: "只能上传.form文件！",
							type: 'error'
						});
						$('.pic_delete').remove();
						$(".file").remove();
						break;;
					default:
						_this.$message({
							message: "服务器繁忙,请稍后重试！",
							type: 'error'
						});
						$('.pic_delete').remove();
						$(".file").remove();
						break;
				}
				switch(err.status) {
					case 550:
						_this.$message({
							message: "文件已上传,不允许上传重复的文件！",
							type: 'error'
						});
						$('.pic_delete').remove();
						$(".file").remove();
						break;
				}
			});
			uploader.bind('removeFile', function(name) {});
			uploader.bind('FileUploaded', function(a, b, c) {
				console.log(c)
				_this.$emit('reFresh');
				_this.$message({
					message: "上传成功",
					type: 'success'
				});
				$('.pic_delete').remove();
				$(".file").remove();
				console.log('111')
			});
			//上传之前设置后端传值
			uploader.bind('BeforeUpload', function(up, file) {
				if(_this.edit.micAddress!=""){
					var micAddress = _this.edit.micAddress.substring(0,4);
				 if(micAddress !="http"){
					_this.$message({
							message: "微服务地址必须是以http开头！",
							type: 'error'
						});
						return
				 }
				}
				if(_this.ruleForm.requestMode==""){
					_this.ruleForm.requestMode ="get"
				}
					uploader.setOption("multipart_params", {
						"status": _this.ruleForm.status,
						"creator": _this.ruleForm.addKey,
						"names": _this.ruleForm.newlyAddName,
						"microServiceAddress": _this.ruleForm.micAddress,
						"requestMode":_this.ruleForm.requestMode
					});
				}),
				//上传按钮
				$('#upload-btn').click(function() {
					_this.ruleForm.newlyAddName = _this.ruleForm.newlyAddName
					if(_this.ruleForm.newlyAddName == "") {
						_this.$message({
							message: "请填写模板名称！",
							type: 'error'
						});
						return;
					} else {
						_this.ruleForm.newlyAddName = _this.ruleForm.newlyAddName
						uploader.start(); //开始上传
					}

				});

			var dataT = {
				page: _this.currentPage.page - 1,
				size: _this.currentPage.pageNum,
				name: _this.searchName,
				keyVal: _this.key,
			}
			$.ajax({
				type: "get",
				url: "http://localhost/activiti-web/form/getPages",
				async: true,
				data: dataT,
				success: function(data) {
					console.log(data)
					_this.tableData = data.content;
					_this.total = data.totalElements;
				},
				error: function(error) {
					console.log(error)
				}
			});
		},
		methods: {
			search() {
				var loading = this.$loading({
					lock: true,
					text: '加载中,请稍后...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				var vm = this;
				var dataT = {
					page: vm.currentPage.page - 1,
					size: vm.currentPage.pageNum,
					name: vm.searchName,
					keyVal: vm.key,
				}
				$.ajax({
					type: "get",
					url: "http://localhost/activiti-web/form/getPages",
					async: true,
					data: dataT,
					success: function(data) {
						console.log(data)
						loading.close()
						vm.tableData = data.content;
						vm.total = data.totalElements;
					},
					error: function(error) {
						loading.close();
						vm.$message.error(data.data.message)
						console.log(error)
					}
				});
			},
			handleSizeChange(val) {
				var vm = this
				console.log(val)
				vm.currentPage.pageNum = val;
				vm.search()
			},
			handleCurrentChange(val) {
				var vm = this
				console.log(`当前页: ${val}`);
				vm.currentPage.page = val
				console.log(vm.currentPage.page)
				vm.search()

			},
			state(type) {
				
				var vm = this;
				console.log(vm.disable)
				if(vm.disable == undefined){
					vm.$message({
							message: '请至少选择一条数据更改状态',
							type: 'error'
						});
				  return true;
				}
				var loading = this.$loading({
					lock: true,
					text: '加载中,请稍后...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				var disable = JSON.parse(JSON.stringify(vm.disable))
				var disableD = [];
				var disData = [];
				
				for(var i = 0; i < disable.length; i++) {
					var status = {};
					status.id = disable[i].id
					if(type == 0) {
						disable[i].status = 0;
					} else {
						disable[i].status = 1;
					}
					status.status = disable[i].status
					disData.push(disable[i].keyVal)
					disableD.push(status)
				}
				console.log(disableD)
				var dataT = {
					statusIds: disableD,
				}
				console.log(dataT)
				$.ajax({
					type: "post",
					url: "http://localhost/activiti-web/form/updateStatus",
					async: true,
					dataType: 'json',
					contentType: 'application/json;charset=UTF-8',
					data: JSON.stringify(disableD),//设置请求类型 
					success: function(data) {
						loading.close();
						vm.$message({
							message: '状态更新成功',
							type: 'success'
						});
						for(var i = 0; i < disData.length; i++) {
							for(var j = 0; j < vm.disable.length; j++) {
								if(vm.disable[j].keyVal == disData[i]) {
									if(type == 0) {
										vm.disable[j].status = 0;
									} else {
										vm.disable[j].status = 1;
									}
								}
							}
						}

					},
					error: function(error) {
						vm.$message.error(data.data.message);
						loading.close();
						console.log(error);
					}
				});
			},
			newlyAdded() {
				var vm = this;
				vm.isNewly = true;
				vm.dialogName = "新增";
				vm.ruleForm.addKey = "";
				$('.prohibit-input input').attr({
					"disabled": false
				});
				$('.prohibit-input input').removeClass('is-disabled');
				$('.pic_delete').remove();
				$(".file").remove();
			},
			editConent(item) {
				console.log(item)
				var vm = this;
				vm.isEditDialog = true;
				vm.dialogName = "编辑";
				vm.edit.addKey = item.keyVal;
				vm.edit.micAddress = item.microServiceAddress;
				vm.edit.id=item.id;
				$('.prohibit-input input').attr({
					"disabled": "disabled"
				});
				$('.prohibit-input input').addClass('is-disabled');
			   this.$http.get("http://localhost/activiti-web/form/findFormTemplate?id="+item.id,).then(
					function(data){
						console.log(data.data.name);
						vm.edit.newlyAddName = data.data.name;
					},function(error){
						vm.$message.error(data.data.message);
					}
				)
			},
			selectChange(value) {
				var vm = this;
				console.log(value)
				vm.disable = value
			},
			handleClose(done) {
				var vm = this
				this.$confirm('确认关闭？')
					.then(_ => {
						vm.isNewly = false;
						vm.isEditDialog = false;
						vm.judgeUpload = true; 
						$('#browse').attr({
						"disabled": false
					});
					$('#upload-btn').attr({
						"disabled": false
					});
					$('#browse').removeClass('is-disabled');
					$('#upload-btn').removeClass('is-disabled');
					})
					.catch(_ => {});
			},
			editCom() {
				console.log( this.edit)
//					url:"http://localhost/activiti-web/form/updateStatusAndNameById?status="+vm.edit.status+"&name="+vm.edit.newlyAddName+"&id="+vm.edit.id,
				var vm = this;
				var dataT ={
					status:vm.edit.status,
					name:vm.edit.newlyAddName,
					id:vm.edit.id,
					microServiceAddress:vm.edit.micAddress
				};
				
				if(vm.edit.newlyAddName ==""){
					vm.$message({
							message: "请编辑模板名称！",
							type: 'error'
						});
						return
				}
				if(vm.edit.micAddress!=""){
					var micAddress = vm.edit.micAddress.substring(0,4);
				 if(micAddress !="http"){
					vm.$message({
							message: "微服务地址必须是以http开头！",
							type: 'error'
						});
						return
				 }
				}
				
				var qs = require('qs');
				var loading = this.$loading({
					lock: true,
					text: '加载中,请稍后...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				this.$http.post("http://localhost/activiti-web/form/updateStatusAndNameById?status="+vm.edit.status+"&name="+vm.edit.newlyAddName+"&id="+vm.edit.id+"&microServiceAddress="+vm.edit.micAddress,).then(
					function(data){
						console.log(data)
						loading.close();
						vm.isEditDialog=false
						vm.search()
					},function(error){
						vm.$message.error(data.data.message);
					}
				)
			},
			close() {				
				$(".model").hide();
				this.$emit('close');
			}
		},
	}
</script>

<style>
	
	.add-dialog {
		display: none;
	}
	
	.show {
		display: none;
	}
	
	.inpt input {
		width: 50%;
	}
	
	.input-message {
		margin-top: 20px;
	}
	
	.definition-info ul li {
		width: 50%;
	}
	
	.process-form {
		padding: 20px 0 10px;
	}
	
	.edit-dialog {
		display: none;
	}
	
	.newly {
		display: block;
		z-index: 1000;
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		/*overflow: auto;*/
		margin: 0;
		background: rgba(127, 127, 127, .5);
	}
	
	.show {
		display: block;
		z-index: 1000;
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		/*overflow: auto;*/
		margin: 0;
		background: rgba(127, 127, 127, .5);
	}
	
	.show .add-dialog-conent {
		z-index: 1001;
		position: fixed;
		top: 50%;
		left: 50%;
		background-color: #000;
		width: 50%;
		height: 60%;
		-webkit-transform: translateX(-50%) translateY(-50%);
		background-color: #FFFFFF;
		width: 90%;
	}
	
	.newly .add-dialog-conent {
		z-index: 1001;
		position: fixed;
		top: 50%;
		left: 50%;
		background-color: #000;
		width: 50%;
		height: 80%;
		-webkit-transform: translateX(-50%) translateY(-50%);
		background-color: #FFFFFF;
		width: 90%;
	}
	
	.add-dialog-conent .table-title li {
		display: block;
		margin-top: 25px;
	}
	
	.add-dialog-conent .table-title span {
		width: 15%;
		display: block;
		text-align: right;
		float: left;
	}
	
	.progress {
		height: 22px;
		font-size: 0;
		line-height: 22px;
		background: #13CE66;
		width: 0;
		color: #000000;
		font-size: 13px;
		margin: 3px 0px;
	}
	
	.model {
		z-index: 1004;
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		opacity: .5;
		background: #000;
		display: none;
	}
	
	.pop h2 {
		width: 100%;
		height: 30px;
		line-height: 30px;
		padding-left: 2em;
		font-size: 14px;
		color: #000;
	}
	

	
	#file-list {
		min-height: 60px;
	}
	
	.file {
		width: 80%;
		margin: 2% 5%;
	}
	
	.exit {
		display: inline-block;
		line-height: 1;
		white-space: nowrap;
		cursor: pointer;
		background: #fff;
		border: 1px solid #bfcbd9;
		border-color: #c4c4c4;
		color: #1f2d3d;
		-webkit-appearance: none;
		text-align: center;
		box-sizing: border-box;
		outline: none;
		margin: 0;
		-moz-user-select: none;
		-webkit-user-select: none;
		-ms-user-select: none;
		padding: 10px 15px;
		font-size: 14px;
		border-radius: 4px;
		float: right;
		margin: 2% 5%;
	}
	
	.is-disabled {
		cursor: not-allowed
	}
	
	.el-message-box__btns {
		text-align: center;
	}
	
	.mar-lef10 {
		margin-left: 10%;
	}
</style>